import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios' // 假设已安装axios
// 设置axios的基础URL
axios.defaults.baseURL = 'https://www.you04.cn'

export const useFileStore = defineStore('file', () => {
  const token = ref(localStorage.getItem('token') || sessionStorage.getItem('token'))
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0,
  })
  //获取文件列表
  const files = ref([])
  const getfiles = async (searchKeyword = '') => {
    try {
      const params = {
        page: pagination.value.page,
        pageSize: pagination.value.pageSize,
      }
      
      // 如果有搜索关键词，添加到参数中
      if (searchKeyword && searchKeyword.trim()) {
        params.keyword = searchKeyword.trim()
      }
      
      const response = await axios.get('/api/files', {
        headers: {
          Authorization: `Bearer ${token.value}`,
        },
        params: params,
      })
      const { items, totalCount, pageIndex, pageSize } = response.data.data
      files.value = items
      pagination.value = {
        page: pageIndex,
        pageSize: pageSize,
        total: totalCount,
      }
      return { files: files.value, pagination: pagination.value }
    } catch (error) {
      throw new Error(error.message || '获取文件失败')
    }
  }
  
  // 设置分页参数
  const setPagination = (page, pageSize) => {
    pagination.value.page = page
    pagination.value.pageSize = pageSize
  }
  //上传文件
  const uploadfiles = async (formData) => {
    // ✅ 接收 formData 作为参数
    try {
      const response = await axios.post('/api/files/upload', formData, {
        // ✅ 用 response 接收返回值
        headers: {
          Authorization: `Bearer ${token.value}`,
        },
      })

      return response.data // ✅ 正确返回数据
    } catch (error) {
      console.error('上传失败:', error.response?.data || error.message)
      throw new Error(error.response?.data?.message || '文件上传失败')
    }
  }
  //下载文件
  // src/api/file.js
  const downloadFile = async (fileId) => {
    try {
      const response = await axios.get(`/api/files/${fileId}/download`, {
        responseType: 'blob',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      })

      // 从响应头获取文件名
      let fileName = `file_${fileId}` // 默认文件名
      const contentDisposition = response.headers['content-disposition']

      if (contentDisposition) {
        const match = contentDisposition.match(/filename="?(.+?)"?$/i)
        if (match?.[1]) {
          fileName = decodeURIComponent(match[1]) // 防止中文乱码
        }
      }

      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', fileName) // 使用后端返回的文件名
      document.body.appendChild(link)
      link.click()
      link.remove()
      window.URL.revokeObjectURL(url)

      return {
        blob: response.data,
        fileName: fileName, // 返回文件名和blob
      }
    } catch (error) {
      console.error('文件下载失败:', error)
      throw new Error(error.response?.data?.message || '文件下载失败')
    }
  }
  //删除文件
  const deleteFile = async (fileId) => {
    try {
      await axios.delete(`/api/files/${fileId}`, {
        headers: {
          Authorization: `Bearer ${token.value}`,
        },
      })

      // 204 No Content 响应没有 data，直接返回
      return
    } catch (error) {
      console.error('删除文件失败:', error)
      throw new Error(error.response?.data?.message || '文件删除失败')
    }
  }
  return {
    token,
    files,
    pagination,
    getfiles,
    uploadfiles,
    downloadFile,
    deleteFile,
    setPagination,
  }
})
